<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!--文件选择框-->
    <input type="file" id="file">
    <!--上传按钮-->
    <button id="btnUpload">上传文件</button>
    <div>
        进度：<span id="per"></span>
    </div>

    <script>
        //获取上传文件的按钮
        var btnUpload = document.querySelector('#btnUpload');
        let perSpan = document.querySelector("#per");
        //为按钮添加click事件监听
        btnUpload.addEventListener('click', function () {
            //再次传输时还原进度条样式
            //获取到选择的文件列表
            var files = document.querySelector('#file').files;
            if (files.length <= 0) {
                return alert('请选择要上传的文件!')
            }
            perSpan.innerHTML = "0";
            // console.log('用户选择了待上传的文件');
            //创建一个FormData对象
            var fd = new FormData();
            //将用户选择的文件添加到FormData中
            fd.append('file', files[0]);

            var xhr = new XMLHttpRequest();
            xhr.timeout = 1000 * 3600 * 12;
            xhr.ontimeout = function (event) {
                alert('上传超时')
            }
            //监听文件上传进度
            let stime = new Date().getTime();
            let sloaded = 0;


            xhr.upload.onprogress = function (e) {
                //e.lengthComputable 是一个布尔值 表示当前上传的资源是否具有可计算的长度
                if (e.lengthComputable) {
                    //e.loaded 已传输的子节
                    //e.total  需要传输的子节
                    //Math.ceil()对一个数进行向上舍入
                    // console.log(percentComplete);
                    //attr() 方法设置或返回被选元素的属性值
                    //动态设置进度条

                    let percentComplete = Math.ceil((e.loaded / e.total) * 100);
                    let endTime = new Date().getTime();
                    let dTime = (endTime - stime) / 1000;
                    let dloaded = e.loaded - sloaded;
                    let speed = dloaded / dTime;
                    speed = speed / 1024;
                    stime = new Date().getTime();
                    sloaded = e.loaded;
                    let speedUnit = "KB/s";
                    if (speed > 1024) {
                        speed = speed / 1024;
                        speedUnit = "MB/s";
                    }
                    speed = speed.toFixed(1);
                    perSpan.innerHTML =`上传进度：${percentComplete}%，上传速度 ：${speed} ${speedUnit}`;
                }
            }

            xhr.upload.onload = function () {
                perSpan.innerHTML = "100%";
            }

            xhr.open('POST', '/upload');
            xhr.send(fd);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);
                    if (data.msg === "ok") {
                        //上传成功
                        alert('上传成功!')
                    } else {
                        //上传失败
                        console.log('图片上传失败!', data.message);
                    }
                }
            }
        })
    </script>
</body>

</html>